package com.carbon.core.util;

import com.carbon.core.lang.Assert;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 拼音转换工具类
 *
 * @author czq
 * @date 2021-03-10
 */
public class PinYinUtils {

    /**
     * 将字符串转换成中文的拼音(小写), 英文 数字 _- 不变, 其他字符全部忽略
     * <blockquote><pre>
     * ==>  你好, hello 123!
     * <==  nihaohello123
     * </pre></blockquote>
     *
     * @param inputString 输入的汉字
     * @return 输出的拼音
     */
    public static String getPinYinLowerCase(String inputString) {
        return getPinYin(inputString, HanyuPinyinCaseType.LOWERCASE, false);
    }

    /**
     * 将字符串转换成 中文拼音的首字符大写, 英文 数字 _- 不变, 其他字符全部忽略
     * <blockquote><pre>
     * ==>  你好, hello 123!
     * <==  NHhello123
     * </pre></blockquote>
     *
     * @param inputString 输入的汉字
     * @return 输出的拼音
     */
    public static String getEveryWordFirstLetterUppercase(String inputString) {
        return getPinYin(inputString, HanyuPinyinCaseType.UPPERCASE, true);
    }

    private static String getPinYin(String inputString, HanyuPinyinCaseType uppercase, boolean isOnlyFirstLetter) {
        Assert.isNotNull(inputString);
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(uppercase);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        StringBuilder output = new StringBuilder();
        if (inputString.length() > 0) {
            char[] input = inputString.trim().toCharArray();
            try {
                for (char c : input) {
                    if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);
                        output.append(isOnlyFirstLetter ? temp[0].substring(0, 1) : temp[0]);
                    } else if (Character.toString(c).matches("[a-zA-Z0-9_\\-]+")) {
                        output.append(c);
                    }
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        }
        return output.toString();
    }

}
